<?php

namespace ApiBundle\Controller\Admin;

use ApiBundle\Controller\BaseController;
use Symfony\Component\HttpFoundation\Request;

class ArticleController extends BaseController
{
    /*
     * 消息列表  is_training 1 通知消息, 2 培训消息
     */
    public function articleListAction(Request $request)
    {
        if(!$this->isAdminLogged()){
            return $this->admin_response;
        }

        $is_training = $request->get("is_training");

        $conn = $this->get("database_connection");

        $page = $request->get("page","1");

        $rows = $request->get("rows","10");

        $admin_role_id = $this->get("session")->get("admin_role_id");


        if($admin_role_id != 4){
            if($is_training == '1'){
                $sql = "SELECT a.* FROM article a LEFT JOIN training t ON a.training_id = t.id WHERE a.training_id IS NULL AND a.district_id = '". $this->getDistrictId() ."' ";
            }

            if($is_training == '2'){
                $sql = "SELECT a.*,t.training_no,t.training_start_at,t.training_end_at,t.training_agency,t.trainer,t.participant,t.training_title_keyword, t.training_agency_keyword FROM article a LEFT JOIN training t ON a.training_id = t.id WHERE training_id IS NOT NULL AND a.district_id = '". $this->getDistrictId() ."' ";
            }

        } else {
            if($is_training == '1'){
                $sql = "SELECT a.* FROM article a LEFT JOIN training t ON a.training_id = t.id WHERE a.training_id IS NULL AND a.admin_id = '". $this->getAdminId() ."' ";
            }

            if($is_training == '2'){
                $sql = "SELECT a.*,t.training_no,t.training_start_at,t.training_end_at,t.training_agency,t.trainer,t.participant,t.training_title_keyword, t.training_agency_keyword FROM article a LEFT JOIN training t ON a.training_id = t.id WHERE training_id IS NOT NULL AND a.admin_id = '". $this->getAdminId() ."' ";
            }
        }



        //搜索
        $search = $request->get("search_keyword");
        if(!empty($search)){
            $sql .= " AND ( a.title LIKE '%". $search ."%' OR t.training_title_keyword LIKE '%". $search ."%' OR t.training_agency_keyword LIKE '%". $search ."%' ) ";
        }


        // 按发布时间搜索
        $start_time = $request->get("start_time");
        $end_time = $request->get("end_time");
        if(!empty($start_time) && !empty($end_time)){
            $sql .= " AND DATE_FORMAT(a.created_at,'%Y-%m-%d') BETWEEN '". $start_time ."' AND '". $end_time ."'  ";
        }


        $sql .= " ORDER BY a.created_at DESC ";


        //搜索条件下的总数
        $search_all_count = count($conn->fetchAll($sql));

        $all_page = ceil($search_all_count / $rows);

        // 分页
        $m = ($page -1) * $rows;

        $sql .= " LIMIT $m,$rows ";


        $data = $conn->fetchAll($sql);


        // 获取已读，未读人数
        foreach($data as &$item){
            $not_count_data = $conn->fetchAll("SELECT * FROM user WHERE id IN (SELECT user_id FROM user_article WHERE article_id = '". $item["id"] ."' AND is_read = 0)");
            $not_count = count($not_count_data);
            $item['is_not_read'] = $not_count;

            $is_count_data = $conn->fetchAll("SELECT * FROM user WHERE id IN (SELECT user_id FROM user_article WHERE article_id = '". $item["id"] ."' AND is_read = 1)");
            $is_count = count($is_count_data);
            $item['is_read'] = $is_count;

            // 已报名，未报名
            if($is_training == "2"){
                $is_apply = $conn->fetchAll("SELECT user_id FROM apply WHERE training_id IN (SELECT training_id FROM article WHERE id = '". $item["id"] ."' ) ");

                $item['is_apply'] = count($is_apply);
                $is_not_apply = $conn->fetchAll("SELECT user_id FROM user_article WHERE article_id = '". $item["id"] ."' AND user_id NOT IN (SELECT user_id FROM apply WHERE training_id = (SELECT training_id FROM article WHERE id = '". $item["id"] ."' ))");
                $item['is_not_apply'] = count($is_not_apply);
            }

        }

        return $this->jsonResponse(0,"操作成功",array("info" => $data,"search_all_count"=>$search_all_count,"all_page"=>$all_page,"curr_date" => date('Y-m-d')));
    }

    /*
     * 消息详情
     */
    public function articleDetailAction(Request $request)
    {
        $id = $request->get("id");
        if(!$this->isAdminLogged()){
            return $this->admin_response;
        }

        if(empty($id)){
            return $this->jsonResponse(1,"参数错误");
        }

        $conn = $this->get("database_connection");
        $data = $conn->fetchAssoc("SELECT ar.*, att.path, att.origin_name, att.size,ad.nickname as admin_nickname, ad.realname as admin_name FROM article ar LEFT JOIN attachment att ON ar.attachment_id = att.id LEFT JOIN admin ad ON ar.admin_id = ad.id  WHERE ar.id = '". $id ."'");

        $data['training_info'] = $conn->fetchAssoc("SELECT * FROM training WHERE id = '". $data["training_id"] ."'");

        return $this->jsonResponse(0,"操作成功",$data);
    }

    /*
     * 发布通知 is_training 0 公告通知 1 培训通知
     */
    public function noticeReleaseAction(Request $request)
    {
        if(!$this->isAdminLogged()){
            return $this->admin_response;
        }

        $conn = $this->get("database_connection");

        $is_training = $request->get("is_training");
        $title = $request->get("title");
        $content = $request->get("content");
        $attachment_id = $request->get("attachment_id");

        $user_ids = $request->get("user_ids","[]");

        $user_id_decode = json_decode($user_ids,TRUE);


        if(empty($title) || empty($content) || empty($attachment_id) || empty($user_ids)){
            return $this->jsonResponse(1,"参数错误");
        }

        if(count($user_id_decode) == 0 ){
            return $this->jsonResponse(1,"请选择接收人");
        }



        // TODO: training 表插入数据
        if($is_training == "1"){
            $training_title_keyword = $request->get("training_title_keyword");
            $training_start_at = $request->get("training_start_at");
            $training_end_at = $request->get("training_end_at");
            $training_agency = $request->get("training_agency");
            $training_agency_keyword = $request->get("training_agency_keyword");
            $trainer = $request->get("trainer");
            $participant = $request->get("participant");

            if(empty($training_title_keyword) || empty($training_start_at) || empty($training_end_at) || empty($training_agency) || empty($training_agency_keyword) || empty($trainer) || empty($participant)){
                return $this->jsonResponse(1,"参数错误");
            }



            $train_mess = array(
                "training_start_at" => $training_start_at,
                "training_end_at" => $training_end_at,
                "training_agency" => $training_agency,
                "trainer" => $trainer,
                "participant" => $participant,
                "training_title_keyword" => $training_title_keyword,
                "training_agency_keyword" => $training_agency_keyword
            );

            $conn->insert("training",$train_mess);
            $training_id = $conn->lastInsertId();

            // 当天年月日十分秒 + 001
//            $trin_num = $training_id%1000;
//            $num = str_pad($trin_num,3,"0",STR_PAD_LEFT);
//            $training_no = date("YmdHis") . $num;

            $training_no = date("YmdHis");

            $conn->update("training",array("training_no" => $training_no),array("id"=>$training_id));

        }


        // TODO: article 表插入数据
        $data = array(
            "title" => $title,
            "content" => $content,
            "attachment_id" => $attachment_id,
            "created_at" => date('Y-m-d H:i:s'),
            "admin_id" => $this->getAdminId(),
            "district_id" => $this->getDistrictId()
        );

        if($is_training == "1"){
            $data['training_id'] = $training_id;
        }


        $conn->insert("article",$data);
        $article_id = $conn->lastInsertId();


        // TODO :user_article 表里插入数据
        foreach($user_id_decode as $item){
            $user_article_create = date("Y-m-d H:i:s");
            $data = array(
                "user_id" => $item,
                "article_id" => $article_id,
                "is_read" => "0",
                "created_at" => $user_article_create
            );
            $conn->insert("user_article",$data);
        }

        return $this->jsonResponse(0,"操作成功");
    }


    /*
     * 获取管理员的所有用户
     */
    public function getUserListAction(Request $request)
    {
        if(!$this->isAdminLogged()){
            return $this->admin_response;
        }

        $conn = $this->get("database_connection");

        $admin_role_id = $this->get("session")->get("admin_role_id");


        $sql = "SELECT u.* FROM user u LEFT JOIN company c ON u.company_id = c.id";

        if($admin_role_id == 4){

            $sql .= " WHERE  u.company_id IN (SELECT id FROM company WHERE  admin_id = '". $this->getAdminId() ."' ) ";
        } else {

            $sql .= " WHERE  u.district_id = '". $this->getDistrictId() ."' ";
        }

        // 搜索
        $user_name = $request->get("user_name");
        $company_name = $request->get("company_name");
        $category_id = $request->get("company_category_id");
        $attribute_id = $request->get("company_attribute_id");
        $admin_id = $request->get("user_admin_id");
        $is_tech_user = $request->get("is_tech_user"); // 1 是 2 否

        if(!empty($user_name)){
            $sql .= " AND u.name = '". $user_name ."' ";
        }

        if(!empty($company_name)){
            $sql .= " AND u.company_full_name = '". $company_name ."' ";
        }

        if(!empty($category_id)){
            $sql .= " AND c.company_category_id = '". $category_id ."' ";
        }

        if(!empty($attribute_id)){
            $sql .= " AND c.company_attribute_id = '". $attribute_id ."' ";
        }

        if(!empty($admin_id)){
            $sql .= " AND c.admin_id = '". $admin_id ."' ";
        }

        if(!empty($is_tech_user)){

            if($is_tech_user == 1){
                $sql .= " AND u.technology_liaisons_status = 1 ";
            } else {
                $sql .= " AND u.technology_liaisons_status != 1 ";
            }

        }


        $data = $conn->fetchAll($sql);
        return $this->jsonResponse(0,"操作成功",$data);
    }

    /*
     * 获取已读,未读人员列表 is_read 0 未读 1 已读
     */
    public function getReadListAction(Request $request)
    {
        if(!$this->isAdminLogged()){
            return $this->admin_response;
        }

        $id = $request->get("id"); // 消息id
        $is_read = $request->get("is_read");

        $page = $request->get("page","1");

        $rows = $request->get("rows","10");

        if(empty($id)){
            return $this->jsonResponse(1,"参数错误");
        }

        $conn = $this->get("database_connection");


        $sql = "SELECT * FROM user WHERE id IN (SELECT user_id FROM user_article WHERE article_id = '". $id ."' AND is_read = '". $is_read ."')";

        //搜索条件下的总数
        $search_all_count = count($conn->fetchAll($sql));

        $all_page = ceil($search_all_count / $rows);

        // 分页
        $m = ($page -1) * $rows;

        $sql .= " LIMIT $m,$rows ";
        $data = $conn->fetchAll($sql);
        $count = count($data);

        return $this->jsonResponse(0,"操作成功",array("info" => $data,"count" => $count,"search_all_count"=>$search_all_count,"all_page"=>$all_page,"curr_page"=>$page,"limit"=>$rows,"article_id"=>$id));
    }

    /*
     * 获取已报名未报名人员列表  is_apply 0 未报名 1 已报名
     */
    public function getApllyListAction(Request $request)
    {
        if(!$this->isAdminLogged()){
            return $this->admin_response;
        }
        $id = $request->get("id"); // 消息id
        $is_apply = $request->get("is_apply");

        $page = $request->get("page","1");

        $rows = $request->get("rows","10");

        if(empty($id)){
            return $this->jsonResponse(1,"参数错误");
        }

        $conn = $this->get("database_connection");

        if($is_apply == "1"){
            $sql = "SELECT * FROM user WHERE id IN( SELECT user_id FROM apply WHERE training_id IN (SELECT training_id FROM article WHERE id = '". $id ."' )  )";
        }

        if($is_apply == "0"){
            $sql = "SELECT * FROM user WHERE id IN (SELECT user_id FROM user_article WHERE article_id = '". $id ."' AND user_id NOT IN (SELECT user_id FROM apply WHERE training_id = (SELECT training_id FROM article WHERE id = '". $id ."' )) )";
        }

        $count = count($conn->fetchAll($sql));


        //搜索条件下的总数
        $search_all_count = count($conn->fetchAll($sql));

        $all_page = ceil($search_all_count / $rows);

        // 分页
        $m = ($page -1) * $rows;

        $sql .= " LIMIT $m,$rows ";

        $data = $conn->fetchAll($sql);


        return $this->jsonResponse(0,"操作成功",array("info" => $data,"count" => $count,"search_all_count"=>$search_all_count,"all_page"=>$all_page,"curr_page"=>$page,"limit"=>$rows,"article_id"=>$id));

    }
}
